import base64
import logging
import traceback
import urllib.request
import time
import json
import uuid
from threading import Timer

from flask import jsonify
from dao.db_connect import db_connect as db
import controller.carbon_alipay.AlipayConfig as AlipayConfig


class UpdateStatus(object):
    @classmethod
    def update_user_after_paying(cls, user_id, vip_time):
        """
        对于购买会员的，需要更新会员状态，这些状态包括：
            · 修改会员等级
            · 刷新vip过期时间
            · 设置 max_times & current_times
        :param user_id: 用户id
        :param vip_time: 需要增加的时间
        :return: bool
        """
        # 修改用户的会员状态
        try:
            # 查询用户状态
            query_sql = f"select id, rank, vip_expire, max_times, current_times, last_expire_time " \
                        f"from user where id = '{user_id}'"
            user_info = db.queryOne(query_sql)
            logging.debug(str(user_info))

            # 更新用户状态
            vip_expire = user_info.get('vip_expire')
            max_times = user_info.get('max_times')
            current_times = user_info.get('current_times')
            last_expire_time = user_info.get('last_expire_time')

            # 更新过期
            if vip_expire is None or vip_expire < int(time.time()):
                max_times = AlipayConfig.default_download_max_times
                current_times = 0
                last_expire_time = int(time.time())
                vip_expire = int(time.time()) + vip_time
            else:  # 延长会员期
                vip_expire = vip_expire + vip_time
            user_rank = 1

            if max_times is None:
                max_times = AlipayConfig.default_download_max_times
            if current_times is None:
                current_times = 0
            if last_expire_time is None:
                last_expire_time = int(time.time())
            # update token
            update_sql = f"update user set rank={user_rank}, vip_expire={vip_expire}, " \
                         f"max_times={max_times}, current_times={current_times}, last_expire_time={last_expire_time} " \
                         f"where id='{user_id}'"
            logging.debug("update user sql:" + update_sql)
            result = db.UpdateOrDeleteOrInsert(update_sql)
            if result is False:
                logging.debug("用户信息更新失败！")
                return False
        except Exception as e:
            logging.debug("用户信息更新失败！")
            return False
        return True

    @classmethod
    def update_files_purchased_after_paying(cls, user_id, good_id, purchase_time):
        """
        :param user_id: 用户id
        :param good_id: 商品id
        :param purchase_time: 购买文件的时间
        :return: bool
        """
        # 查询用户
        query_sql = f"select id from user where id = '{user_id}'"
        user_info = db.queryOne(query_sql)
        if user_info is None:
            logging.error(f"user_id: {user_id} 用户不存在！")
            return False

        # 检查是否存在该文件
        query_sql = f"select id from files_info where good_id = '{good_id}'"
        file_info = db.queryOne(query_sql)
        if file_info is None:
            logging.error(f"file_info: {file_info} 文件不存在！")
            return False

        # 检查是否已经购买该文件
        file_id = file_info.get('id')
        if file_id is None:
            logging.error(f"file_id: {file_id} 文件不存在！")
            return False
        query_sql = f"select uid, fid, purchase_time from files_purchased where uid = '{user_id}' and fid = '{file_id}'"
        file_info = db.queryOne(query_sql)
        if file_info is not None:
            logging.error(f"user_id: {user_id}, file_info: {file_info} 该文件被重复购买！")
            return False

        insert_sql = f"insert into files_purchased values('{user_id}', '{file_id}', '{purchase_time}')"
        logging.debug("insert files_purchased sql:" + insert_sql)
        result = db.UpdateOrDeleteOrInsert(insert_sql)
        if result is False:
            logging.error(f"user_id: {user_id}, file_info: {file_info} 文件购买记录插入失败！")
            return False
        return True
